package com.loong.game2048.controller;

import com.loong.game2048.Exception.BizException;
import com.loong.game2048.Exception.BizExceptionCodeEnum;
import com.loong.game2048.annotation.Authorize;
import com.loong.game2048.module.Comment;
import com.loong.game2048.module.Forum;
import com.loong.game2048.module.ResultCode;
import com.loong.game2048.module.vo.Result;
import com.loong.game2048.server.CommentServer;
import com.loong.game2048.server.ForumServer;
import com.loong.game2048.server.UserServer;
import com.loong.game2048.util.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentServer commentServer;
    @Autowired
    private ForumServer forumServer;
    @Autowired
    private UserServer userServer;

    /**
     * 评论帖子
     * @param comment:
     *               parent_id:被评论的帖子id
     *               content:评论内容
     * @return
     */
    @Authorize
    @PostMapping("/pubComment")
    public Result pubComment(@RequestBody Comment comment,
                             HttpServletRequest request) {


        if (comment.getContent() == null){
            Result result = new Result();
            result.setCode(ResultCode.PARAMETER_ERROR);
            result.setMsg("评论内容不可为空！");
            return result;
        }

        //获取用户ID
        String openId = ResultUtils.getOpenId(request);
        comment.setUId(openId);
        comment.setType(1);

        Integer fid = comment.getParentId();
        Forum forum = forumServer.findById(fid);
        if (forum == null){
            throw new BizException(BizExceptionCodeEnum.FORUM_NOT_FOUND);
        }

        return commentServer.pubComment(comment);

    }

    /**
     *回复功能（二级评论）
     * @param comment:
     *          parent_id:被回复的Comment的ID
     *          content:评论内容
     * @param request
     * @return
     */
    @Authorize
    @PostMapping("/reComment")
    public Result reply(@RequestBody Comment comment,
                        HttpServletRequest request){

        if (comment.getContent() == null){
            Result result = new Result();
            result.setCode(ResultCode.PARAMETER_ERROR);
            result.setMsg("评论内容不可为空！");
            return result;
        }

        //获取用户ID
        String openId = ResultUtils.getOpenId(request);
        comment.setUId(openId);
        comment.setType(2);

        //插入数据库
        return commentServer.reply(comment);
    }

}
